#coding=utf-8
import uliweb.form as form
from uliweb.form import *

class AssForm(form.Form):
    def post_html(self):
        from uliweb.core.js import json_dumps
        from uliweb import settings
        
        buf = """
<script>
    jQuery.fn.extend({
        selectLink:function(ids,id,JSON){
            $(ids).change(function(){
                var b = [];html = '';
                $(id).html(html);
                var c = $(ids).val();
                b = JSON[c];
                if(b != ''){
                    for(var j in b){html = html + '<option value=' + b[j][0] + '>' + b[j][1] + '</option>'}
                    $(id).html(html);
                }
            })
        }
    }); 
    //js页面
    $(document).ready(function(){
        $().selectLink('#field_type','#field_stage',stage)
    });
    var stage = %s;
</script>
    """ % json_dumps(settings.PARA.ASSIGNMENT_STAGE)
        
        return buf

    def validate_ass_id(self, data):
        from uliweb.orm import get_model
                 
        A = get_model('assignment')
        a = A.get(A.c.ass_id == data)
        if a:
            return '任务书编号已经存在，请检查'
    
class AssEditForm(AssForm):
    def validate_ass_id(self, data):
        from uliweb.orm import get_model
                 
        A = get_model('assignment')
        a = A.filter(A.c.ass_id == data)
        for x in a:
            if x.id != self.assignment.id:
                return '任务书编号已经存在，请检查'
    
    def form_validate(self, data):
        from datetime import date

        error = {}
        
        if data.get('acceptance_finish_date') and data['acceptance_finish_date'] > date.today():
            error['acceptance_finish_date'] = '验收完成日期不能大于当前系统日期'
            
        if data.get('finish_date') and data['finish_date'] > date.today():
            error['finish_date'] = '实际完成日期不能大于当前系统日期'
            
        return error